package cn.com.dhc.danlu.activity.coupon;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.coupon.model.GoodsCoupon;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CalculatePriceUtil;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.hd.mall.web.webservices.entity.freedom.entity.coupon.CouponEntity;
import cn.com.hd.mall.web.webservices.entity.freedom.request.coupon.GetDealerCouponParamReq;
import cn.com.hd.mall.web.webservices.entity.freedom.response.coupon.GetDealerCouponParamResponse;
import cn.com.hd.mall.web.webservices.entity.request.shoppingcart.CreateOrderRequest.SellerListBean.DealerCouponListBean;
import cn.com.hd.mall.web.webservices.entity.request.shoppingcart.CreateOrderRequest.SellerListBean.MerchListBean.DealerBenefitBean;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.ToShoppingcartResponse.SellerListBean.MerchListBean.PromotionModelListBean;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;
import static cn.com.dhc.danlu.util.CalculatePriceUtil.addition;


/**
 * User: Geek_Soledad(wuhaiyang@danlu.com)
 * Date: 2016-10-10
 * Time: 17:54
 * Description: 维护 下单使用商品优惠券 & 经销商红包  逻辑
 */
public class DeductionLogicKeeper {
    //经销商ID -> （（商品model）商品ID & 商品优惠券） size 不变  GoodsCoupon.dealerBenefits动态变化
    private final ArrayMap<String, List<GoodsCoupon>> mGoodsDiscountMaps = new ArrayMap<>();
    // 经销商ID - > 经销商红包
    private final ArrayMap<String, List<CouponEntity>> mSellerEnvelopMaps = new ArrayMap<>();
    // 经销商Id -> 经销商参数
    private final ArrayMap<String, Integer> mDealerParams = new ArrayMap<>();

    private Context mContext;
    private List<String> mDealerIds;
    private String mTmpDealerId;

    public DeductionLogicKeeper(Context context) {
        mContext = context;
    }

    public void setDealerIds(List<String> dealerIds) {
        mDealerIds = dealerIds;
        batchQueryDealerParams(mDealerIds, false);
    }

    public String getDealerPayRatioById(String sellerId) {
        Integer ratio = mDealerParams.get(sellerId);
        if (null != ratio) {
            return ratio.intValue() + "";
        }
        return null;
    }

    public void putDealerGoodsList(String dealerId, List<GoodsCoupon> models) {
        boolean isContain = mGoodsDiscountMaps.containsKey(dealerId);
        if (isContain) {
            return;
        }
      /*  //计算当前商品优惠券实际使用金额
        calculateCouponActUse (models);*/
        mGoodsDiscountMaps.put(dealerId, models);
    }

    /**
     * 点击经销商红包跳转逻辑
     *
     * @return true
     */
    public void gotoDealerEnvelop(@NonNull final String dealerId) {
        this.mTmpDealerId = dealerId;
        if (mDealerParams.isEmpty()) {
            batchQueryDealerParams(mDealerIds, true);
        } else {
            String bdMaxDeduction = getDealerMaxDeduction(dealerId).toPlainString();
            // 指定经销商下 商品优惠券总额
            String totalDeduction = getSelectGoodsCouponAmount(dealerId);
            int compare = CalculatePriceUtil.compare(totalDeduction, bdMaxDeduction);
            if (compare == 1 || compare == 0) {
                ToastUtil.getInstance().show(CommonUtils.getStringByResId(R.string.dl_settlement_beyond_payratio), CommonUtils.getStringByResId(R.string.smile_tips), false);
                return;
            } else {
                List<CouponEntity> entityList = mSellerEnvelopMaps.get(dealerId);
                String selectEnvelopJsonStr = "";
                if (null != entityList && !entityList.isEmpty()) {
                    selectEnvelopJsonStr = CommonUtils.parseBean2Json(entityList);
                }
                // 计算当前可以使用经销商红包的最大抵扣金额 =  最大抵扣 - 之前优惠券抵扣
                BigDecimal maxHighDeductionDealerEnvelopAmount = CalculatePriceUtil.subtraction(bdMaxDeduction, totalDeduction);
                //跳转到使用经销商红包界面
                UseDealersEnvelopActivity.startSelf((Activity) mContext, selectEnvelopJsonStr, dealerId, maxHighDeductionDealerEnvelopAmount.toPlainString(), getPromotionDiscountTotalGoodsAmout(dealerId), Integer.MAX_VALUE);
            }
        }
    }

    /**
     * 切换某一个经销商下的商品优惠券
     *
     * @param entity
     *         null or entity
     *
     * @return true --> 存在 宿主activity中的丹露红包清空
     */
    public boolean changeDealerGoodsBenefits(String dealerId, String goodsId, @Nullable DealerBenefitBean entity) {
        List<GoodsCoupon> coupons = mGoodsDiscountMaps.get(dealerId);
        if (null != coupons && !coupons.isEmpty()) {
            for (GoodsCoupon goodsCoupon : coupons) {
                if (goodsCoupon.getMerchId().equals(goodsId)) {
                    goodsCoupon.setDealerBenefits(entity);
                    clearDealerEnvelop(dealerId);
                    return true;
                }
            }
        }
        Log.w("@@@@ L55", "DeductionLogicKeeper:changeDealerGoodsBenefits() -> " + "do not buy goods in " + dealerId);
        return false;
    }

    /**
     * 清空指定经销商红包  清除丹露红包的操作放置于宿主activity中
     */
    private void clearDealerEnvelop(String dealerId) {
        mSellerEnvelopMaps.remove(dealerId);
    }

    /**
     * 选择经销商红包后调用
     */
    public void onUseDealerEnvelopResult(String dealerId, List<CouponEntity> selectDealerEnvelop) {
        if (null == selectDealerEnvelop) {
            selectDealerEnvelop = new ArrayList<>();
        }
        mSellerEnvelopMaps.put(dealerId, selectDealerEnvelop);
    }

    /**
     * 获取使用经销商红包实际抵扣金额
     */
    public BigDecimal getDealerEnvelopFactUseById(String dealerId) {
        List<CouponEntity> couponEntityList = mSellerEnvelopMaps.get(dealerId);
        BigDecimal total = new BigDecimal(0);
        if (null != couponEntityList) {
            for (CouponEntity entity : couponEntityList) {
                total = CalculatePriceUtil.addition(total.toPlainString(), entity.getFactUse());
            }
        }
        return total;
    }

    /**
     * 所有经销商下所有商品优惠券实际抵扣
     */
    public BigDecimal getTotalCouponDeduction() {
        BigDecimal bdTotal = new BigDecimal(0);
        for (int i = 0; i < mGoodsDiscountMaps.size(); i++) {
            List<GoodsCoupon> values = mGoodsDiscountMaps.valueAt(i);
            // 重新计算下商品优惠券实际抵扣
            calculateCouponActUse(values);
            if (null != values && !values.isEmpty()) {
                for (GoodsCoupon goodsCoupon : values) {
                    DealerBenefitBean dealerBenefits = goodsCoupon.getDealerBenefits();
                    if (null != dealerBenefits) {
                        bdTotal = CalculatePriceUtil.addition(bdTotal.toPlainString(), dealerBenefits.getCouponUseAmt());
                    }
                }
            }
        }
        return bdTotal;
    }

    /**
     * 获取所有经销商下所有商品优惠券面额
     */
    public BigDecimal getTotalCouponAmount() {
        BigDecimal bdTotal = new BigDecimal(0);
        for (int i = 0; i < mGoodsDiscountMaps.size(); i++) {
            List<GoodsCoupon> values = mGoodsDiscountMaps.valueAt(i);
            if (null != values && !values.isEmpty()) {
                for (GoodsCoupon goodsCoupon : values) {
                    DealerBenefitBean dealerBenefits = goodsCoupon.getDealerBenefits();
                    if (null != dealerBenefits) {
                        bdTotal = CalculatePriceUtil.addition(bdTotal.toPlainString(), dealerBenefits.getCouponAmt());
                    }
                }
            }
        }
        return bdTotal;
    }


    /**
     * 计算经销商优惠券实际使用金额
     */
    private void calculateCouponActUse(List<GoodsCoupon> models) {
        if (null == models || models.isEmpty()) return;
        for (GoodsCoupon goodsCoupon : models) {
            DealerBenefitBean benefits = goodsCoupon.getDealerBenefits();
            if (null != benefits) {
                String couponAmt = benefits.getCouponAmt();
                BigDecimal goodsTotalAmount = getGoodsTotalAmount(goodsCoupon);
                int compare = CalculatePriceUtil.compare(couponAmt, goodsTotalAmount.toPlainString());
                if (compare == 1) {
                    benefits.setCouponUseAmt(goodsTotalAmount.toPlainString());
                } else {
                    benefits.setCouponUseAmt(couponAmt);
                }
                goodsCoupon.setDealerBenefits(benefits);
            }
        }
    }

    /**
     * 获取商品总价 = 商品单价 * 数量 ；受促销类型制约
     */
    public BigDecimal getGoodsTotalAmount(GoodsCoupon model) {
        String unitPrice = model.getUnitPrice(); //商品单价
        String merchQuantity = model.getMerchQuantity();
        PromotionModelListBean promotionModel = model.getPromotionModel();
        BigDecimal deductionAfter;
        if (null != promotionModel) {
            String reduceType = promotionModel.getReductionType();
            String diffPrice = promotionModel.getDiffPrice();
            if (!TextUtils.isEmpty(reduceType)) {
                if (reduceType.equals(CommonConst.PromotionConst.REDUCTION_TYPE_0)) {
                    // 满减单
                    String singlePrice = CalculatePriceUtil.subtraction(unitPrice, diffPrice).toPlainString();
                    deductionAfter = CalculatePriceUtil.multiplication(singlePrice, merchQuantity);
                } else if (reduceType.equals(CommonConst.PromotionConst.REDUCTION_TYPE_1)) {
                    // 满减总
                    String originTotal = CalculatePriceUtil.multiplication(unitPrice, merchQuantity).toPlainString();
                    deductionAfter = CalculatePriceUtil.subtraction(originTotal, diffPrice);
                } else {
                    deductionAfter = CalculatePriceUtil.multiplication(unitPrice, merchQuantity);
                }
            } else {
                deductionAfter = CalculatePriceUtil.multiplication(unitPrice, merchQuantity);
            }
        } else {
            deductionAfter = CalculatePriceUtil.multiplication(unitPrice, merchQuantity);
        }
        return deductionAfter;
    }

    /**
     * 获取所有经销商 红包抵扣金额
     */
    public BigDecimal getTotalDealersEnvelopDeduction() {
        BigDecimal bdTotal = new BigDecimal(0);
        // 遍历
        for (int i = 0; i < mSellerEnvelopMaps.size(); i++) {
            List<CouponEntity> values = mSellerEnvelopMaps.valueAt(i);
            if (null != values && !values.isEmpty()) {
                for (CouponEntity entity : values) {
                    bdTotal = CalculatePriceUtil.addition(entity.getFactUse(), bdTotal.toPlainString());
                }
            }
        }
        return bdTotal;
    }

    /**
     * 获取所有经销商 红包面额 --> 用于大额红包验证
     */
    public BigDecimal getTotalDealersEnvelopAmount() {
        BigDecimal bdTotal = new BigDecimal(0);
        // 遍历
        for (int i = 0; i < mSellerEnvelopMaps.size(); i++) {
            List<CouponEntity> values = mSellerEnvelopMaps.valueAt(i);
            if (null != values && !values.isEmpty()) {
                for (CouponEntity entity : values) {
                    bdTotal = CalculatePriceUtil.addition(entity.getCouponAmt(), bdTotal.toPlainString());
                }
            }
        }
        return bdTotal;
    }

    /**
     * 获取指定经销商下选择红包 ：构建请求参数
     */
    public List<DealerCouponListBean> getHasSelectDealerEnvelopsById(String dealerId) {
        List<CouponEntity> entityList = mSellerEnvelopMaps.get(dealerId);
        if (null == entityList || entityList.isEmpty()) {
            return null;
        }
        ArrayList<DealerCouponListBean> res = new ArrayList<>();
        for (CouponEntity entity : entityList) {
            DealerCouponListBean dealerCouponEntity = new DealerCouponListBean();
            dealerCouponEntity.setDealerCouponCode(entity.getCouponCode());
            dealerCouponEntity.setDealerCouponAmt(entity.getCouponAmt());
            dealerCouponEntity.setDealerCouponUseAmt(entity.getFactUse());
            res.add(dealerCouponEntity);
        }
        return res;
    }

    /**
     * 获取指定经销商下 指定商品列表的 优惠券信息-> 构建请求参数
     */
    public DealerBenefitBean getGoodsBenefit(String goodsId, String sellerId) {
        List<GoodsCoupon> couponList = mGoodsDiscountMaps.get(sellerId);
        if (null == couponList || couponList.isEmpty()) {
            return null;
        }
        for (GoodsCoupon goodsCoupon : couponList) {
            if (goodsCoupon.getMerchId().equals(goodsId)) {
                return goodsCoupon.getDealerBenefits();
            }
        }
        return null;
    }

    /**
     * 获取 商品信息&优惠券信息
     */
    public GoodsCoupon getGoodsModelById(String dealerId, String goodsId) {
        List<GoodsCoupon> coupons = mGoodsDiscountMaps.get(dealerId);
        if (null != coupons && !coupons.isEmpty()) {
            for (GoodsCoupon coupon : coupons) {
                if (coupon.getMerchId().equals(goodsId)) {
                    return coupon;
                }
            }
        }
        return null;
    }

    /**
     * 批量查询
     *
     * @param subsequent
     *         是否存在后续操作
     */
    private void batchQueryDealerParams(List<String> dealerIds, final boolean subsequent) {
        if (null == dealerIds || dealerIds.isEmpty()) {
            return;
        }
        agent.getApi()
                .getDealerCouponParam(new GetDealerCouponParamReq(agent.getToken(), dealerIds))
                .compose(OperatorUtils.<GetDealerCouponParamResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<GetDealerCouponParamResponse>() {
                    @Override
                    protected void onSuccess(GetDealerCouponParamResponse model) {
                        List<GetDealerCouponParamResponse.DealerParamEntity> list = model.getParamList();
                        for (GetDealerCouponParamResponse.DealerParamEntity entity : list) {
                            mDealerParams.put(entity.getDealerId(), entity.getDealerPayRatio());
                        }
                        if (subsequent && !TextUtils.isEmpty(mTmpDealerId)) {
                            if (null != mDealerParams.get(mTmpDealerId)) {
                                gotoDealerEnvelop(mTmpDealerId);
                            }
                        }
                    }
                });
    }

    /**
     * 获取指定经销商下 所有商品使用的优惠券金额
     */
    private String getSelectGoodsCouponAmount(String dealerId) {
        List<GoodsCoupon> goodsCoupons = mGoodsDiscountMaps.get(dealerId);
        String res = "0";
        if (goodsCoupons != null && !goodsCoupons.isEmpty()) {
            for (GoodsCoupon goodsCoupon : goodsCoupons) {
                DealerBenefitBean benefits = goodsCoupon.getDealerBenefits();
                if (null != benefits) {
                    //  //价值面额
                    res = CalculatePriceUtil.addition(res, benefits.getCouponUseAmt()).toPlainString();
                }
            }
        }
        return res;
    }

    /**
     * 获取指定经销商最大抵扣金额
     * 满减单 ： （unitPrice - diffPrice） * count
     * 满减总： unitPrice * count - diffPrice
     */
    private BigDecimal getDealerMaxDeduction(String dealerId) {
        List<GoodsCoupon> currentGoodsList = mGoodsDiscountMaps.get(dealerId);
        BigDecimal bdTotal = new BigDecimal(0);
        for (GoodsCoupon model : currentGoodsList) {
            bdTotal = addition(bdTotal.toPlainString(), getGoodsTotalAmount(model).toPlainString());
        }
        //商品总价*最高支付比
        int payRatio = mDealerParams.get(dealerId);
        //百分比 = 支付比 / 10000 如：30% = 3000 / 10000;
        BigDecimal divide = CalculatePriceUtil.divide(String.valueOf(payRatio), String.valueOf(10000));
        return CalculatePriceUtil.multiplication(divide.toPlainString(), bdTotal.toPlainString());
    }

    /**
     * 获取指定经销商下所有商品总额（扣除满减满增后）
     */
    private String getPromotionDiscountTotalGoodsAmout(String dealerId) {
        List<GoodsCoupon> goodsCoupons = mGoodsDiscountMaps.get(dealerId);
        BigDecimal bdTotal = new BigDecimal(0);
        if (null != goodsCoupons && !goodsCoupons.isEmpty()) {
            for (GoodsCoupon goodsCoupon : goodsCoupons) {
                bdTotal = CalculatePriceUtil.addition(bdTotal.toPlainString(), getGoodsTotalAmount(goodsCoupon).toPlainString());
            }
        }
        // 排除小数的可能性
        return CalculatePriceUtil.intercept(bdTotal.toPlainString());
    }
}
